from flask import request, jsonify
from flaskapp.entity.User import User
from flaskapp.entity.House import House
from flaskapp.entity.Rent import Rent
from flaskapp.util.Redprint import Redprint
from flaskapp.util.Result import Result
from flaskapp.util.jwt_optional_for_options import jwt_optional_for_options
from sqlalchemy import func
from flaskapp.util.Sqlalchemy import db

api = Redprint('admin')

@api.route('/users', methods=['GET', 'OPTIONS'])
@jwt_optional_for_options
def get_users():
    """获取所有用户信息"""
    try:
        # 从请求头获取token并验证管理员权限
        payload = request.jwt_payload
        if not payload.get('is_admin'):
            return Result.error(403, '只有管理员才能访问此接口')

        # 获取筛选参数
        account_name = request.args.get('account_name', '')
        username = request.args.get('username', '')
        is_admin = request.args.get('is_admin', type=int)

        # 构建查询
        query = User.query

        # 应用筛选条件
        if account_name:
            query = query.filter(User.account_name.like(f'%{account_name}%'))
        if username:
            query = query.filter(User.username.like(f'%{username}%'))
        if is_admin is not None:
            query = query.filter(User.is_admin == bool(is_admin))

        # 获取所有用户
        users = query.all()
        result = []
        for user in users:
            result.append(user.to_dict())

        return jsonify(result)
    except Exception as e:
        return Result.error(500, f'服务器错误: {str(e)}')

@api.route('/users/<int:user_id>', methods=['GET', 'OPTIONS'])
@jwt_optional_for_options
def get_user(user_id):
    """获取指定用户信息"""
    try:
        # 从请求头获取token并验证管理员权限
        payload = request.jwt_payload
        if not payload.get('is_admin'):
            return Result.error(403, '只有管理员才能访问此接口')

        user = User.query.get(user_id)
        if not user:
            return Result.error(404, '用户不存在')

        return Result.success(user.to_dict(), '获取用户信息成功')
    except Exception as e:
        return Result.error(500, f'服务器错误: {str(e)}')

@api.route('/statistics', methods=['GET', 'OPTIONS'])
@jwt_optional_for_options
def get_statistics():
    """获取统计数据"""
    try:
        # 从请求头获取token并验证管理员权限
        payload = request.jwt_payload
        if not payload.get('is_admin'):
            return Result.error(403, '只有管理员才能访问此接口')

        # 获取普通用户数量（非管理员）
        normal_users_count = User.query.filter_by(is_admin=False).count()

        # 获取总房源数
        total_houses = House.query.count()

        # 获取总出租房源数（通过rent表统计）
        total_rented = Rent.query.distinct(Rent.house_id).count()

        # 获取总收入（rent表中amount的总和）
        total_income = db.session.query(func.sum(Rent.amount)).scalar() or 0

        # 获取各种房型的数量
        one_room = House.query.filter(House.house_type.like('%1室%')).count()
        two_room = House.query.filter(House.house_type.like('%2室%')).count()
        three_room = House.query.filter(House.house_type.like('%3室%')).count()
        four_room = House.query.filter(House.house_type.like('%4室%')).count()

        # 构建响应数据
        statistics = {
            'normal_users_count': normal_users_count,  # 普通用户数量
            'total_houses': total_houses,              # 总房源数
            'total_rented': total_rented,             # 总出租数
            'total_income': float(total_income),      # 总收入
            'house_types': {                          # 各种房型数量
                'one_room': one_room,                 # 一室
                'two_room': two_room,                 # 两室
                'three_room': three_room,             # 三室
                'four_room': four_room                # 四室
            }
        }

        return jsonify(statistics)
    except Exception as e:
        return Result.error(500, f'服务器错误: {str(e)}')


@api.route('/users/<int:user_id>/life', methods=['PUT'])
@jwt_optional_for_options
def update_user_life(user_id):
    """禁用/解封用户"""
    payload = request.jwt_payload
    if not payload.get('is_admin'):
        return Result.error(403, '只有管理员可以执行此操作')

    data = request.get_json()
    life = data.get('life')
    if life not in (0, 1):
        return Result.error(400, 'life 参数必须为 0 或 1')

    user = User.query.get(user_id)
    if not user:
        return Result.error(404, '用户不存在')

    user.life = life
    db.session.commit()
    return Result.success(200,msg='用户状态已更新')
